import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Select, Button, Row, Col, Table, Space, Tag, Popconfirm, message, Dropdown, Tree, Modal, InputNumber, DatePicker } from 'antd';
import { SearchOutlined, ReloadOutlined, PlusOutlined, SettingOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import type { Dayjs } from 'dayjs';
import { categoryService } from './server';
import { Category, CategoryStatus, CategoryListParams } from './server';
import './index.less';

const { Option } = Select;
const { TreeNode } = Tree;

// 分类状态标签组件
const CategoryStatusTag: React.FC<{ status?: CategoryStatus }> = ({ status }) => {
  switch(status) {
    case CategoryStatus.Enabled:
      return <Tag color="success">启用</Tag>;
    case CategoryStatus.Disabled:
      return <Tag color="error">禁用</Tag>;
    default:
      return <Tag color="default">未知</Tag>;
  }
};

// 表格列定义
const getColumns = (
  handleEdit: (record: Category) => void,
  handleDelete: (id: string | number) => void
): ColumnsType<Category> => [
  {
    title: '分类编码',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '分类名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '级别',
    dataIndex: 'level',
    key: 'level',
    render: (level?: number) => level === 1 ? '一级分类' : level === 2 ? '二级分类' : `${level}级分类`,
  },
  {
    title: '上级分类',
    dataIndex: 'parentId',
    key: 'parentId',
    render: (parentId?: string | number) => parentId === 0 ? '无' : `${parentId}`,
  },
  {
    title: '排序',
    dataIndex: 'sortOrder',
    key: 'sortOrder',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (status?: CategoryStatus) => <CategoryStatusTag status={status} />,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    render: (_text, record) => (
      <Space size="middle">
        <Button
          type="text"
          icon={<EditOutlined />}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Popconfirm
          title="确定删除该分类吗?"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            type="text" 
            danger 
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Popconfirm>
      </Space>
    ),
  },
];

// 可选的表单项
const formItems = [
  { label: '分类名称', key: 'name', component: <Input placeholder="请输入分类名称" /> },
  { label: '分类编码', key: 'code', component: <Input placeholder="请输入分类编码" /> },
  { 
    label: '分类级别', 
    key: 'level', 
    component: (
      <Select placeholder="请选择分类级别" allowClear>
        <Option value={1}>一级分类</Option>
        <Option value={2}>二级分类</Option>
      </Select>
    ) 
  },
  { 
    label: '上级分类', 
    key: 'parentId', 
    component: (
      <Select placeholder="请选择上级分类" allowClear>
        <Option value={0}>无</Option>
      </Select>
    ) 
  },
  { 
    label: '分类状态', 
    key: 'status', 
    component: (
      <Select placeholder="请选择分类状态" allowClear>
        <Option value={CategoryStatus.Enabled}>启用</Option>
        <Option value={CategoryStatus.Disabled}>禁用</Option>
      </Select>
    ) 
  },
  {
    label: '创建时间',
    key: 'createTimeRange',
    component: <DatePicker.RangePicker style={{ width: '100%' }} />
  },
];

// 定义表单值类型
interface CategoryFormValues {
  name?: string;
  code?: string;
  level?: number;
  parentId?: string | number;
  status?: CategoryStatus;
  createTimeRange?: [Dayjs, Dayjs];
}

// 定义分类编辑表单类型
interface CategoryEditFormValues {
  id?: string | number;
  name: string;
  code: string;
  level: number;
  parentId: string | number;
  description?: string;
  status: CategoryStatus;
  sortOrder: number;
}

export const CategoryList: React.FC = () => {
  // 搜索表单
  const [form] = Form.useForm<CategoryFormValues>();
  // 编辑表单
  const [editForm] = Form.useForm<CategoryEditFormValues>();
  
  // 分类列表数据
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<Category[]>([]);
  const [total, setTotal] = useState<number>(0);
  
  // 分页设置
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  
  // 搜索表单显示项配置
  const [searchConfig, setSearchConfig] = useState<Record<string, boolean>>(() => {
    // 从本地存储获取配置，如果没有则默认全部显示
    const savedConfig = localStorage.getItem('categorySearchConfig');
    if (savedConfig) {
      return JSON.parse(savedConfig);
    }
    return formItems.reduce((config, item) => ({
      ...config,
      [item.key]: true,
    }), {});
  });
  
  // 配置选择器可见性
  const [configVisible, setConfigVisible] = useState<boolean>(false);
  
  // 编辑模态框可见性和当前编辑的分类
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);
  
  // 上级分类选项
  const [parentOptions, setParentOptions] = useState<Category[]>([]);
  
  // 表单配置树
  const FormItemConfig = () => (
    <Dropdown
      visible={configVisible}
      onVisibleChange={setConfigVisible}
      overlay={
        <Card title="配置搜索项" style={{ width: 200 }}>
          <Tree
            checkable
            defaultCheckedKeys={Object.entries(searchConfig)
              .filter(([_, value]) => value)
              .map(([key]) => key)}
            onCheck={(checkedKeys) => handleConfigChange(checkedKeys as string[])}
          >
            {formItems.map(item => (
              <TreeNode key={item.key} title={item.label} />
            ))}
          </Tree>
        </Card>
      }
      trigger={['click']}
    >
      <Button icon={<SettingOutlined />}>配置显示搜索项</Button>
    </Dropdown>
  );
  
  // 初始加载和重新加载数据
  useEffect(() => {
    loadData({
      page: pagination.current,
      pageSize: pagination.pageSize,
    });
    loadParentOptions();
  }, []);
  
  // 加载分类列表数据
  const loadData = async (params: CategoryListParams) => {
    setLoading(true);
    try {
      const result = await categoryService.getCategoryList(params);
      setData(result.list);
      setTotal(result.total);
    } catch (error) {
      message.error('获取分类列表失败');
      console.error('获取分类列表失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  // 加载上级分类选项
  const loadParentOptions = async () => {
    try {
      const categories = await categoryService.getAllCategories();
      // 只保留一级分类作为父级选项
      const parentCategories = categories.filter(cat => cat.level === 1);
      setParentOptions(parentCategories);
    } catch (error) {
      message.error('获取上级分类选项失败');
      console.error('获取上级分类选项失败:', error);
    }
  };
  
  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    setPagination({
      current: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
    });
    
    const formValues = form.getFieldsValue();
    const params: CategoryListParams = {
      page: newPagination.current || 1,
      pageSize: newPagination.pageSize || 10,
    };
    
    // 添加其他搜索条件
    if (formValues.name) {
      params.keyword = formValues.name;
    }
    if (formValues.parentId !== undefined) {
      params.parentId = formValues.parentId;
    }
    if (formValues.status !== undefined) {
      params.status = formValues.status;
    }
    if (formValues.createTimeRange && formValues.createTimeRange.length === 2) {
      params.startDate = formValues.createTimeRange[0].format('YYYY-MM-DD');
      params.endDate = formValues.createTimeRange[1].format('YYYY-MM-DD');
    }
    
    loadData(params);
  };
  
  // 处理搜索表单配置变更
  const handleConfigChange = (checkedKeys: string[]) => {
    const newConfig = formItems.reduce((config, item) => ({
      ...config,
      [item.key]: checkedKeys.includes(item.key),
    }), {});
    
    setSearchConfig(newConfig);
    localStorage.setItem('categorySearchConfig', JSON.stringify(newConfig));
    setConfigVisible(false);
  };
  
  // 处理搜索按钮点击
  const handleSearch = () => {
    const formValues = form.getFieldsValue();
    const params: CategoryListParams = {
      page: 1,
      pageSize: pagination.pageSize,
    };
    
    // 重置分页为第一页
    setPagination({
      ...pagination,
      current: 1,
    });
    
    // 添加搜索条件
    if (formValues.name) {
      params.keyword = formValues.name;
    }
    if (formValues.parentId !== undefined) {
      params.parentId = formValues.parentId;
    }
    if (formValues.status !== undefined) {
      params.status = formValues.status;
    }
    if (formValues.createTimeRange && formValues.createTimeRange.length === 2) {
      params.startDate = formValues.createTimeRange[0].format('YYYY-MM-DD');
      params.endDate = formValues.createTimeRange[1].format('YYYY-MM-DD');
    }
    
    loadData(params);
  };
  
  // 处理重置按钮点击
  const handleReset = () => {
    form.resetFields();
    setPagination({
      ...pagination,
      current: 1,
    });
    loadData({
      page: 1,
      pageSize: pagination.pageSize,
    });
  };
  
  // 处理编辑按钮点击
  const handleEdit = (record: Category) => {
    setCurrentCategory(record);
    editForm.setFieldsValue({
      id: record.id,
      name: record.name,
      code: record.code,
      level: record.level,
      parentId: record.parentId,
      description: record.description,
      status: record.status,
      sortOrder: record.sortOrder,
    });
    setEditModalVisible(true);
  };
  
  // 处理删除按钮点击
  const handleDelete = async (id: string | number) => {
    try {
      await categoryService.deleteCategory(id);
      message.success('删除分类成功');
      loadData({
        page: pagination.current,
        pageSize: pagination.pageSize,
      });
    } catch (error) {
      message.error('删除分类失败');
      console.error('删除分类失败:', error);
    }
  };
  
  // 处理创建按钮点击
  const handleCreate = () => {
    setCurrentCategory(null);
    editForm.resetFields();
    editForm.setFieldsValue({
      level: 1,
      parentId: 0,
      status: CategoryStatus.Enabled,
      sortOrder: 1,
    });
    setEditModalVisible(true);
  };
  
  // 处理编辑表单提交
  const handleEditFormSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      if (currentCategory) {
        // 更新分类
        await categoryService.updateCategory({
          ...currentCategory,
          ...values,
        });
        message.success('更新分类成功');
      } else {
        // 创建分类
        await categoryService.createCategory(values);
        message.success('创建分类成功');
      }
      setEditModalVisible(false);
      loadData({
        page: pagination.current,
        pageSize: pagination.pageSize,
      });
    } catch (error) {
      console.error('表单提交失败:', error);
    }
  };
  
  // 处理编辑表单取消
  const handleEditFormCancel = () => {
    setEditModalVisible(false);
  };
  
  // 根据级别渲染不同的父级选择
  const renderParentSelect = () => {
    const level = editForm.getFieldValue('level');
    if (level === 1) {
      return (
        <Select placeholder="一级分类无需选择上级分类" disabled>
          <Option value={0}>无</Option>
        </Select>
      );
    } else {
      return (
        <Select placeholder="请选择上级分类">
          {parentOptions.map(option => (
            <Option key={option.id} value={option.id}>{option.name}</Option>
          ))}
        </Select>
      );
    }
  };
  
  return (
    <div className="category-list-container">
      <Card bordered={false} className="search-card">
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={handleSearch}
        >
          <Row gutter={24}>
            {/* 根据配置动态渲染搜索表单项 */}
            {formItems.map(item => (
              searchConfig[item.key] && (
                <Col span={6} key={item.key}>
                  <Form.Item label={item.label} name={item.key}>
                    {item.component}
                  </Form.Item>
                </Col>
              )
            ))}
            
            {/* 按钮区域 */}
            <Col span={24} style={{ textAlign: 'right' }}>
              <Space>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                  搜索
                </Button>
                <Button icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
                  新建
                </Button>
                <FormItemConfig />
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>
      
      <Card bordered={false} className="table-card">
        <Table
          columns={getColumns(handleEdit, handleDelete)}
          rowKey="id"
          dataSource={data}
          pagination={{
            ...pagination,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          loading={loading}
          onChange={handleTableChange}
        />
      </Card>
      
      {/* 分类编辑弹窗 */}
      <Modal
        title={currentCategory ? '编辑分类' : '新建分类'}
        visible={editModalVisible}
        onOk={handleEditFormSubmit}
        onCancel={handleEditFormCancel}
        width={600}
        destroyOnClose
      >
        <Form
          form={editForm}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
        >
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          
          <Form.Item
            name="code"
            label="分类编码"
            rules={[{ required: true, message: '请输入分类编码' }]}
          >
            <Input placeholder="请输入分类编码" />
          </Form.Item>
          
          <Form.Item
            name="level"
            label="分类级别"
            rules={[{ required: true, message: '请选择分类级别' }]}
          >
            <Select 
              placeholder="请选择分类级别"
              onChange={() => {
                // 当级别改变时，重置父级ID
                if (editForm.getFieldValue('level') === 1) {
                  editForm.setFieldsValue({ parentId: 0 });
                } else {
                  editForm.setFieldsValue({ parentId: undefined });
                }
              }}
            >
              <Option value={1}>一级分类</Option>
              <Option value={2}>二级分类</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="parentId"
            label="上级分类"
            rules={[{ required: true, message: '请选择上级分类' }]}
          >
            {renderParentSelect()}
          </Form.Item>
          
          <Form.Item
            name="description"
            label="分类描述"
          >
            <Input.TextArea rows={4} placeholder="请输入分类描述" />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="分类状态"
            rules={[{ required: true, message: '请选择分类状态' }]}
          >
            <Select placeholder="请选择分类状态">
              <Option value={CategoryStatus.Enabled}>启用</Option>
              <Option value={CategoryStatus.Disabled}>禁用</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="sortOrder"
            label="排序"
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <InputNumber min={1} style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}; 